define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'pt/major/index' + location.search,
                    add_url: 'pt/major/add',
                    edit_url: 'pt/major/edit',
                    del_url: 'pt/major/del',
                    multi_url: 'pt/major/multi',
                    import_url: 'pt/major/import',
                    table: 'pt_major',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: '',
                escape: true,
                pagination: false,
                search: false,
                commonSearch: false,
                rowAttributes: function (row, index) {
                    // 默认只显示系列，隐藏类别和专业
                    if (row.type === 'series') {
                        return {}; // 系列显示
                    } else {
                        return {style: "display:none"}; // 类别和专业默认隐藏
                    }
                },
                columns: [
                    [
                        // {checkbox: false},
                        
                        //{field: 'id', title: __('Id')},
                        {field: 'type', title: __('Type'), operate: false, formatter: function (value, row, index) {
                            if (value == 'series') {
                                return '职称系列';
                            } else if (value == 'category') {
                                return '职称类别';
                            } else {
                                return '评审专业';
                            }
                        }},
                        {field: 'major_code', title: __('Major_code'), operate: 'LIKE'},
                        {field: 'name', title: __('Major_name'), operate: 'LIKE', align: 'left', formatter: Controller.api.formatter.title, clickToSelect: !false},
                        {field: 'pid', title: __('Parent_id'), formatter: function (value, row, index) {
                            if (row.type === 'series') {
                                return '-';
                            } else if (row.type === 'category') {
                                return row.series_id ? '系列ID:' + row.series_id : '-';
                            } else {
                                return row.category_id ? '类别ID:' + row.category_id : '-';
                            }
                        }},
                        {field: 'create_time', title: __('Create_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'update_time', title: __('Update_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                             formatter: function (value, row, index) {
                                var that = $.extend({}, this);
                                var table = $(that.table).clone(true);//通过that去引用table中的信息
                                if (row.type == 'series') {
                                    // 移除删除按钮的权限标识
                                    $(table).data("operate-del",null);//隐藏操作中的删除按钮，
                                }
                                that.table = table;//更新that.table的值，让默认的格式化方法使用新的table
                                
                                return Table.api.formatter.operate.call(that,value,row,index);//展示信息中的操作按钮
                            }
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            // 绑定系列筛选事件
            $('select[name="series_id"]').on('change', function() {
                var seriesId = $(this).val();
                // 重新加载表格数据
                table.bootstrapTable('refresh', {
                    query: {
                        series_id: seriesId
                    }
                });
            });
            
            // 绑定树形结构展开/收起事件
            $(document).on('click', '.btn-node-sub', function () {
                var id = $(this).data('id');
                var type = $(this).data('type');
                var caret = $(this).find('i.fa-caret-right, i.fa-caret-down');
                
                if (caret.length > 0) {
                    // 切换展开/收起状态
                    if (caret.hasClass('fa-caret-right')) {
                        caret.removeClass('fa-caret-right').addClass('fa-caret-down');
                        // 显示子节点
                        showChildren(table, id, type);
                    } else {
                        caret.removeClass('fa-caret-down').addClass('fa-caret-right');
                        // 隐藏子节点
                        hideChildren(table, id);
                    }
                }
            });
            
            // 显示子节点的函数
            function showChildren(table, parentId, parentType) {
                table.find('tbody tr').each(function() {
                    var rowData = $(this).data('index');
                    if (rowData !== undefined) {
                        var tableData = table.bootstrapTable('getData');
                        var row = tableData[rowData];
                        if (row && row.pid == parentId) {
                            $(this).show();
                            // 只显示直接子节点，不自动展开更深层级
                            // 移除自动展开更深层级的逻辑
                        }
                    }
                });
            }
            
            // 隐藏子节点的递归函数
            function hideChildren(table, parentId) {
                table.find('tbody tr').each(function() {
                    var rowData = $(this).data('index');
                    if (rowData !== undefined) {
                        var tableData = table.bootstrapTable('getData');
                        var row = tableData[rowData];
                        if (row && row.pid == parentId) {
                            var childId = row.id;
                            $(this).hide();
                            // 递归隐藏子节点
                            hideChildren(table, childId);
                        }
                    }
                });
            }

        },
        add: function () {
            Controller.api.bindevent();
            // 监听联动选择器变化
            Controller.api.bindParentSelect();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            formatter: {
                title: function (value, row, index) {
                    value = value.toString().replace(/(&|&amp;)nbsp;/g, '&nbsp;');
                    
                    // 根据类型显示不同的图标和样式
                    var caret = '';
                    var className = '';
                    var styleClass = '';
                    
                    if (row.type === 'series') {
                        caret = '<i class="fa fa-caret-right"></i>';
                        className = 'text-primary';
                        styleClass = 'font-weight-bold';
                    } else if (row.type === 'category') {
                        caret = '<i class="fa fa-caret-right"></i>';
                        className = 'text-success';
                        styleClass = 'font-weight-bold';
                    } else {
                        className = 'text-muted';
                    }
                    
                    value = caret + value;
                    value = "<span class='" + styleClass + "'>" + value + "</span>";
                    
                    return '<a href="javascript:;" data-id="' + row.id + '" data-type="' + row.type + '" class="'
                        + className + ' btn-node-sub">' + value + '</a>';
                }
            },
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            bindParentSelect: function () {
                // 监听系列选择变化
                $('select[name="row[series_id]"]').on('change', function() {
                    var seriesId = $(this).val();
                    var categoryId = $('select[name="row[category_id]"]').val();
                    
                    if (categoryId && categoryId !== '') {
                        // 如果选择了类别，设置parent_id为类别ID
                        $('#c-parent_id').val(categoryId);
                    } else if (seriesId && seriesId !== '') {
                        // 如果只选择了系列，设置parent_id为系列ID
                        $('#c-parent_id').val(seriesId);
                    } else {
                        // 没有选择任何父级，设置为0
                        $('#c-parent_id').val(0);
                    }
                });
                
                // 监听类别选择变化
                $('select[name="row[category_id]"]').on('change', function() {
                    var categoryId = $(this).val();
                    var seriesId = $('select[name="row[series_id]"]').val();
                    
                    if (categoryId && categoryId !== '') {
                        // 选择了类别，设置parent_id为类别ID
                        $('#c-parent_id').val(categoryId);
                    } else if (seriesId && seriesId !== '') {
                        // 只选择了系列，设置parent_id为系列ID
                        $('#c-parent_id').val(seriesId);
                    } else {
                        // 没有选择任何父级，设置为0
                        $('#c-parent_id').val(0);
                    }
                });
            }
        }
    };
    return Controller;
});
